package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.function.Consumer;

@Component
@Slf4j
public class UserJob {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 每日工单量列表初始化
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception{
        //todo:查询用户列表
        //工单初始化
        try {
            userService.list().forEach(new Consumer<UserEntity>() {
                @Override
                public void accept(UserEntity userEntity) {
                    if (!"1001".equals(userEntity.getRoleCode())){
                        //todo:构建数据（zset）
                        String key= VMSystem.REGION_TASK_KEY_PREF
                                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))   //日期
                                +"."+ userEntity.getRegionId()   //区域
                                +"."+userEntity.getRoleCode();   //角色code
                        redisTemplate.opsForZSet().add(key,userEntity.getId().toString(),0);
                        redisTemplate.expire(key, Duration.ofDays(1));
                    }
                }
            });
            return ReturnT.SUCCESS;
        }catch (Exception e){
            return ReturnT.FAIL;
        }

    }

}
